<?php

namespace App\Http\Controllers\Auth;

use App\Events\SendSms;
use App\Http\Controllers\BaseController;
use App\Mail\SendCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Overtrue\EasySms\EasySms;

class BindController extends BaseController
{
    public function __construct()
    {
        $this->middleware('check.phone.code')->only('updatePhone');
        $this->middleware('check.email.code')->only('updateEmail');
    }

    /**
     * 获取邮件的验证码
     */
    public function emailCode(Request $request)
    {
        $request->validate([
            'email'=>'required|email|unique:users'
        ],[
            'email.required' => '邮箱 不能为空',
            'email.email' => '邮箱 格式不合法',
            'email.unique' => '邮箱 已存在',
        ]);
        // 发送验证码到邮件
        Mail::to($request->input('email'))->queue(new SendCode($request->input('email')));

        return $this->response->noContent();
    }
    /**
     * 更新邮件
     */
    public function updateEmail(Request $request)
    {
        $request->validate([
            'email' => 'unique:users'
        ],[
            'email.unique' => '邮箱 已存在',
        ]);
        // 更新邮箱
        $user = auth('api')->user();
        $user->email = $request->input('email');
        $user->save();
        return $this->response->noContent();

    }
    /**
     * 获取手机的验证码
     */
    public function phoneCode(Request $request)
    {
        $request->validate([
            'phone' => 'required|regex:/^1[3-9]\d{9}$/|unique:users'
        ],[
            'phone.required' => '手机号码 不能为空',
            'phone.regex' => '手机号码 格式不对',
            'phone.unique' => '手机号码 已存在',
        ]);

        // 发送短信事件
        SendSms::dispatch($request->input('phone'), '绑定手机');
        // //发送验证码到手机
        // $config = config('sms');
        // $easySms = new EasySms($config);
        // $code = rand(1000,9999);
        //
        // //缓存验证码
        // // Cache::put('phone_code_'.$event->phone,$code,now()->addMinutes(15));
        // // Cache::forget('phone_code_'.$event->phone);
        //
        // try {
        //     $easySms->send($request->input('phone'),[
        //         'template' => $config['template'],
        //         'data' => [
        //             'code' => $code,
        //             'product' => '绑定手机'
        //         ]
        //     ]);
        //
        // }catch (\Exception $e){
        //     return $e->getExceptions();
        // }
        return $this->response->noContent();
    }
    /**
     * 更新手机号码
     */
    public function updatePhone(Request $request)
    {
        // 更新手机号
        $user = auth('api')->user();
        $user->email = $request->input('email');
        $user->save();
        return $this->response->noContent();

    }
}
